package com.ywu.standard.gateway.handler;

import com.ywu.common.gson.GsonUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

public interface HandlerInterface {
    String OPEN_SERVICE_PREFIX = "openService";

    /**
    * @Author GroundDemo
    * @Description 成返回值
    * @Date 11:22 2024/5/26
    * @Param [serverWebExchange, obj]
    * @return reactor.core.publisher.Mono<java.lang.Void>
    **/
    default Mono<Void> generateResponseInfo(ServerWebExchange serverWebExchange, Object obj) {
        String jsonStr = GsonUtils.serialize(obj);
        ServerHttpResponse response = serverWebExchange.getResponse();
        byte[] bits = jsonStr.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /**
    * @Author GroundDemo
    * @Description 判断当前路由是否为openService
    * @Date 9:40 2024/9/28
    * @Param [serverWebExchange]
    * @return boolean
    **/
    default boolean isOpenService(ServerWebExchange serverWebExchange) {
        String url = serverWebExchange.getRequest().getPath().toString();
        if (url.startsWith("/")) {
            url = url.substring(1);
        }
        return url.startsWith(OPEN_SERVICE_PREFIX);
    }
}
